package com.automannn.springPractice.applicationContext.bean.lookup;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * 注释配置应用程序作为ioc容器测试
 *
 * @author chenkh
 * @time 2021/8/20 11:35
 * @date 2022/08/03
 */
public class SafeBeanTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(SafeBeanTest.class);
        context.refresh();
        getBean(context);
        getBeanByObjectFactory(context);
        getBeanOfType(context);
        getBeanProvider(context);
        context.close();
    }

    public static void getBean(AnnotationConfigApplicationContext context) {
        printTrance("getBean", () -> context.getBean(User.class));
    }

    public static void getBeanByObjectFactory(AnnotationConfigApplicationContext context) {
        ObjectFactory<User> beanFactory = context.getBeanProvider(User.class);
        printTrance("getBeanByObjectFactory", beanFactory::getObject);
    }

    public static void getBeanOfType(AnnotationConfigApplicationContext context) {
        ListableBeanFactory beanFactory = context.getBeanFactory();
        printTrance("getBeanOfType", () -> beanFactory.getBeanNamesForType(User.class));
    }

    public static void getBeanProvider(AnnotationConfigApplicationContext context) {
        ObjectProvider<User> objectProvider = context.getBeanProvider(User.class);
        printTrance("getBeanProvider", () -> objectProvider.forEach(System.out::println));
    }

    public static void printTrance(String source, Runnable runnable) {
        System.err.println(String.format("方法来源：%s", source));
        try {
            runnable.run();
        } catch (BeansException e) {
            e.printStackTrace();
        }
        System.err.println("==================================================================");
    }
}
